//
//  WHTransReconizeController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/7.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHTransReconizeController.h"
#import <AVFoundation/AVFoundation.h>
#import "WHReconizeInfoView.h"
#import <AipOcrSdk/AipOcrService.h>
#import "WHConfirmView.h"
#import "WHExpressSelectView.h"
#import "WHExpressModel.h"
#import "WHMsgChargeController.h"
#import <Photos/Photos.h>

typedef NS_ENUM(NSUInteger, CheckType) {
    CheckTypeUnknow,
    CheckTypeBarcode, // 订单编号
    CheckTypePhoneNumber, // 手机号码
};

@interface WHTransReconizeController ()

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureStillImageOutput *output; // 照片输出

@property (nonatomic, strong) WHReconizeInfoView *infoView;
@property (nonatomic, copy) NSString *expressName; // 快递名称
@property (nonatomic, strong) WHDeliverModel *deliverModel; // 快递员

@property (nonatomic, copy) void (^successHandler)(id);
@property (nonatomic, copy) void (^failHandler)(NSError *error);

@property (nonatomic, copy) NSString *barCodeStr;
@property (nonatomic, copy) NSString *phoneNumberStr;
@property (nonatomic, strong) UIImage *currentImage; // 当前拍摄的图片
@property (nonatomic, assign) BOOL isFindBarCodeStr;
@property (nonatomic, assign) BOOL isFindPhoneNumberStr;

@property (nonatomic, strong) WHExpressSelectView *expressSelectView;
@property (nonatomic, strong) UIView *desBackView;
@property (nonatomic, strong) UILabel *desLabel;
@property (nonatomic, strong) UIButton *captureBtn;

@end

@implementation WHTransReconizeController

- (void)saveImageToAsset:(nonnull UIImage *)image {
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusDenied ) { // 用户拒绝当前App访问权限
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                    [WHView showAlertwithTitle:@"用户拒绝授权" message:@"请去-> [设置 - 隐私 - 照片 - 松鼠侠] 选择读取和写入" okTitle:@"去设置" okAction:^(UIAlertAction *action) {
                        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                            [[UIApplication sharedApplication] openURL:settingURL];
                        }
                    } cacelTitle:@"取消" cancelAction:^(UIAlertAction *action) {
                        
                    }];
                }
            } else if (status == PHAuthorizationStatusAuthorized) { // 用户允许当前App访问
                [self saveImage:image];
            } else if (status == PHAuthorizationStatusRestricted) { // 无法访问相册
                [WHView showAlertwithTitle:nil message:@"无法访问相册" okAction:nil cancelAction:nil];
            }
        });
    }];
}

- (void)saveImage:(nonnull UIImage *)image  {
    NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
    // 查询所有自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    PHAssetCollection *assetCollection = nil;
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {
            assetCollection = collection;
            break;
        }
    }
    
    // 当前对应的app相册没有被创建,创建一个自定义相册
    if (assetCollection == nil) {
        NSError *error = nil;
        __block NSString *createCollectionID = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            createCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
        assetCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createCollectionID] options:nil].firstObject;
    }
    
    // 先保存图片到相册
    NSError *error = nil;
    __block PHObjectPlaceholder *placeholder = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        placeholder =  [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
    } error:&error];
    if (error) {
        DLog(@"保存失败");
        return;
    }
    if (assetCollection == nil) {
        DLog(@"创建相册失败");
    }
    // 将刚才保存到相册里面的图片引用到自定义相册
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        PHAssetCollectionChangeRequest *requtes = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        [requtes insertAssets:@[placeholder] atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    if (error) {
        DLog(@"引用图片失败");
    } else {
        DLog(@"引用图片成功");
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"面单识别";
    self.naviType = NaviTypeClear;
    
    [self setUpUI];
    [self configCallback];
}

- (void)setUpUI {
    
    WHReconizeInfoView *infoView = [[WHReconizeInfoView alloc] init];
    [self.view addSubview:infoView];
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(kRealwidth(55));
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    kWeakSelf(self);
    infoView.selectExpress = ^{
        [weakself selectExpressInfo];
    };
    
    _infoView = infoView;
    [self configInfoView];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            [WHView showAlertwithTitle:@"用户拒绝授权" message:@"请去-> [设置 - 隐私 - 相机 - 松鼠侠] 打开相机访问权限" okTitle:@"去设置" okAction:^(UIAlertAction *action) {
                NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                    [[UIApplication sharedApplication] openURL:settingURL];
                }
            } cacelTitle:@"取消" cancelAction:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
        } else {
            [self loadCaptureView];
        }
    } else {
        DLog(@"不支持摄像机");
        [WHView showAlertwithTitle:nil message:@"不支持摄像机"];
    }
}

- (void)loadCaptureView {
    UIView *captureView = [[UIView alloc] init];
    [self.view addSubview:captureView];
    [captureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self.view);
        make.bottom.mas_equalTo(_infoView.mas_top);
    }];
    
    UIView *desBackView = [[UIView alloc] init];
    desBackView.backgroundColor = HexColor(@"ffeae5");
    [captureView addSubview:desBackView];
    desBackView.hidden = YES;
    [desBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(captureView);
        make.bottom.mas_equalTo(captureView.mas_bottom);
        make.height.mas_equalTo(kRealwidth(33));
    }];
    _desBackView = desBackView;
    
    UILabel *desLabel = [[UILabel alloc] init];
    desLabel.backgroundColor = HexColor(@"ffeae5");
    desLabel.textColor = CMDarkOrangeColor;
    desLabel.font = SYSTEMFONT(kRealwidth(12));
    [desBackView addSubview:desLabel];
    [desLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(desBackView.mas_left).offset(kRealwidth(15));
        make.right.mas_equalTo(desBackView.mas_right).offset(-kRealwidth(15));
        make.top.bottom.mas_equalTo(desBackView);
    }];
    _desLabel = desLabel;
    
    UIButton *captureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [captureBtn setImage:IMAGE_NAMED(@"capture_btn_icon") forState:UIControlStateNormal];
    [captureView addSubview:captureBtn];
    [captureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(captureView.mas_centerX);
        make.bottom.mas_equalTo(captureView.mas_bottom).offset(-kRealwidth(30));
        make.width.height.mas_equalTo(kRealwidth(60));
    }];
    [captureBtn addTarget:self action:@selector(photoClicked:) forControlEvents:UIControlEventTouchUpInside];
    _captureBtn = captureBtn;
    
    UIButton *lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [lightBtn setImage:IMAGE_NAMED(@"light_btn_icon") forState:UIControlStateNormal];
    [captureView addSubview:lightBtn];
    [lightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(captureView.mas_right).offset(-kRealwidth(30));
        make.top.mas_equalTo(captureView.mas_top).offset(kTopHeight+kRealwidth(30));
        make.width.height.mas_equalTo(kRealwidth(35));
    }];
    [lightBtn addTarget:self action:@selector(lightClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    // 获取摄像设备
//    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDevice *device;
    NSArray *deviceArray = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *backDevice in deviceArray) {
        if (backDevice.position == AVCaptureDevicePositionBack) {
            device = backDevice;
        }
    }
    
    [device lockForConfiguration:nil];
    if ([device isFlashModeSupported:AVCaptureFlashModeAuto]) {
        [device setFlashMode:AVCaptureFlashModeAuto];
    }
    if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
        [device setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
    }
    if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
        [device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
    }
    [device unlockForConfiguration];
    
    // 创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
//    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    self.output = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *setDic = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
    self.output.outputSettings = setDic;
    
    // 初始化链接对象
    self.session = [[AVCaptureSession alloc] init];
    // 高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    [self.view layoutIfNeeded];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = captureView.layer.bounds;
    [captureView.layer insertSublayer:layer atIndex:0];
    
    [self.view bringSubviewToFront:_infoView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.session) {
        [self.session startRunning];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.session) {
        [self.session stopRunning];
    }
}

- (void)configInfoView {
    if (self.expressName) {
        _infoView.expressNameLabel.text = self.expressName;
    } else {
        _infoView.expressNameLabel.text = @"请选择快递和快递员";
    }
    if (self.deliverModel) {
        _desBackView.hidden = NO;
        _desLabel.text = NSStringFormat(@"结算员余额%@,还可以录入%@件", self.deliverModel.balance, self.deliverModel.residue);
        _infoView.courierLabel.text = self.deliverModel.expressName;
        [_captureBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.bottom.mas_equalTo(_desBackView.mas_top).offset(-kRealwidth(30));
            make.width.height.mas_equalTo(kRealwidth(60));
        }];
    } else {
        _desBackView.hidden = YES;
        _infoView.courierLabel.text = @"";
    }
}

- (void)configCallback {
    __weak typeof(self) weakSelf = self;
    
    // 这是默认的识别成功的回调
    _successHandler = ^(id result) {
        
        DLog(@"result:%@", result);
        if (result[@"words_result"]){
            if ([result[@"words_result"] isKindOfClass:[NSDictionary class]]) {
                [result[@"words_result"] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    if ([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]) {
                        
                        [weakSelf checkStr:obj[@"words"]];
                    } else {
                        [weakSelf checkStr:obj];
                    }
                    
                }];
            } else if ([result[@"words_result"] isKindOfClass:[NSArray class]]) {
                for (NSDictionary *obj in result[@"words_result"]){
                    if ([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        [weakSelf checkStr:obj[@"words"]];
                    }
                }
            }
            
        } else {
            [weakSelf checkStr:result];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            
            WHConfirmView *confirmView = [[WHConfirmView alloc] init];
            [kAppWindow addSubview:confirmView];
            [confirmView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(kAppWindow);
            }];
            confirmView.numberField.text = weakSelf.barCodeStr;
            confirmView.phoneField.text = weakSelf.phoneNumberStr;
            
            confirmView.numberChange = ^(NSString * _Nonnull text) {
                weakSelf.barCodeStr = text;
            };
            confirmView.phoneChange = ^(NSString * _Nonnull text) {
                weakSelf.phoneNumberStr = text;
            };
            
            confirmView.okClicked = ^{
                [weakSelf expressInto];
            };
            confirmView.cancelClicked = ^{
                [WHView showHudMsg:@"取消入库"];;
            };
        });
    };
    
    _failHandler = ^(NSError *error){
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            DLog(@"%@", error);
            [WHView showAlertwithTitle:nil message:@"识别失败" okAction:nil cancelAction:nil];
        });
        
    };
}

- (void)resetCheck {
    _barCodeStr = nil;
    _phoneNumberStr = nil;
    _isFindBarCodeStr = NO;
    _isFindPhoneNumberStr = NO;
    _currentImage = nil;
}

#pragma mark - —————— 事件 ——————

- (void)selectExpressBy:(NSArray *)dataArray headerTitle:(NSString *)headerTitle bottomTitle:(NSString *)bottomTitle selectExpress:(selectExpress)select {
    WHExpressSelectView *expressSelectView = [[WHExpressSelectView alloc] initWithArray:dataArray headerTitle:headerTitle bottomTitle:bottomTitle];

    [expressSelectView show];
    expressSelectView.selectExpress = select;
    _expressSelectView = expressSelectView;
}

- (void)photoClicked:(UIButton *)button {
    if (!self.expressName || !self.deliverModel) {
        [WHView showAlertwithTitle:nil message:@"请先选择快递和快递员!" okAction:^(UIAlertAction *action) {
            [self selectExpressInfo];
        } cancelAction:nil];

        return;
    }
    
    [self resetCheck];
    
    AVCaptureConnection *connection = [self.output connectionWithMediaType:AVMediaTypeVideo];
    if (connection) {
        [self.output captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
            
            if (!imageDataSampleBuffer) {
                [WHView showAlertwithTitle:nil message:@"无法识别" okAction:nil cancelAction:nil];
            } else {
                NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                UIImage *image = [UIImage imageWithData:imageData];
                _currentImage = image;
                
                DLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
                [self saveImageToAsset:image];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                DLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
                    NSDictionary *options = @{@"language_type": @"CHN_ENG", @"detect_direction": @"true"};
                    [MBProgressHUD showLoadHUDMsg:@"识别中"];
                    
                    [[AipOcrService shardService] detectTextAccurateBasicFromImage:image
                                                                       withOptions:options
                                                                    successHandler:_successHandler
                                                                       failHandler:_failHandler];
                });
            }
        }];
    } else {
        [WHView showAlertwithTitle:nil message:@"无法识别" okAction:nil cancelAction:nil];
    }
}

- (void)lightClicked:(UIButton *)button {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            [device lockForConfiguration:nil];
            if (device.torchMode == AVCaptureTorchModeOn) {
                [device setTorchMode:AVCaptureTorchModeOff];
            } else if (device.torchMode == AVCaptureTorchModeOff) {
                [device setTorchMode:AVCaptureTorchModeOn];
            }
            [device unlockForConfiguration];
        }
    }
}

- (void)checkStr:(NSString *)checkeStr {
    if (!_isFindBarCodeStr || !_isFindPhoneNumberStr) {
        CheckType checkType = [self checkStrType:checkeStr];
        if (checkType == CheckTypeBarcode) {
            if (!_isFindBarCodeStr) {
                _isFindBarCodeStr = YES;
                _barCodeStr = checkeStr;
            }
        } else if (checkType == CheckTypePhoneNumber) {
            if (!_isFindPhoneNumberStr) {
                _isFindPhoneNumberStr = YES;
                _phoneNumberStr = checkeStr;
            }
        }
    }
}

- (CheckType)checkStrType:(NSString *)checkeStr {
    if ([WHValidationHelper validateMobile:checkeStr]) {
        return CheckTypePhoneNumber;
    }
    if ([self isBarCode:checkeStr]) {
        return CheckTypeBarcode;
    }
    return CheckTypeUnknow;
}

- (BOOL)isBarCode:(NSString *)checkedNumString {
    NSString *barCodeRegex = @"^[a-zA-Z0-9]+$";
    NSPredicate *barCodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", barCodeRegex];
    return [barCodePredicate evaluateWithObject:checkedNumString];
}

- (void)showChargeAlert {
    [WHView showAlertwithTitle:@"短信套餐不足10条" message:@"短信不足会造成入库失败,请尽快充值" okTitle:@"充值" okAction:^(UIAlertAction *action) {
        [_expressSelectView dismiss];
        WHMsgChargeController *charge = [[WHMsgChargeController alloc] init];
        [self.navigationController pushViewController:charge animated:YES];
    } cacelTitle:@"取消" cancelAction:nil];
}

#pragma mark - —————— 接口 ——————
- (void)selectExpressInfo {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_clickExpressInto);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          nil];
    
    kWeakSelf(self);
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                NSNumber *stationSurplus = retDict[@"stationSurplus"];
                
                if (stationSurplus.intValue < 10) {
                    [self showChargeAlert];
                }
                
                NSArray *params = retDict[@"params"];
                
                NSMutableArray *expressNameArray = @[].mutableCopy;
                NSMutableArray *expressArray = @[].mutableCopy;
                for (NSDictionary *expressDict in params) {
                    WHExpressModel *expressModel = [WHExpressModel modelWithJSON:expressDict];
                    [expressNameArray addObject:expressModel.expressName];
                    [expressArray addObject:expressModel];
                }
                
                [weakself selectExpressBy:expressNameArray headerTitle:@"请选择快递" bottomTitle:@"下一步" selectExpress:^(NSInteger selectIndex) {
                    weakself.expressName = expressNameArray[selectIndex];
                    
                    WHExpressModel *expressModel = expressArray[selectIndex];
                    
                    NSMutableArray *deliverNameArray = @[].mutableCopy;
                    for (WHDeliverModel *deliverModel in expressModel.data) {
                        [deliverNameArray addObject:deliverModel.expressName];
                    }
                    
                    [weakself selectExpressBy:deliverNameArray headerTitle:@"请选择快递员" bottomTitle:@"完成" selectExpress:^(NSInteger selectIndex) {
                        WHDeliverModel *deliverModel = expressModel.data[selectIndex];
                        weakself.deliverModel = deliverModel;
                        
                        [weakself configInfoView];
                    }];
                }];
                
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)expressInto {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_expressInto);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.deliverModel.expressUserId, @"expressUserId",
                          self.barCodeStr, @"waybillNum",
                          self.phoneNumberStr, @"mobile",
                          self.expressName, @"expressCompany",
                          nil];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *imageName = [formatter stringFromDate:[NSDate date]];
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSArray *nameArray = @[@"imgFile"];
    [MBProgressHUD showHudInView:nil];
    [manger POST:postURL parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < nameArray.count; i++) {
            UIImage *image = self.currentImage;
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            DLog(@"upMyService image size: %ld k", (long)(imageData.length / 1024));
            NSString *fileName = NSStringFormat(@"%@-%d.png", imageName, i);
            [formData appendPartWithFileData:imageData name:nameArray[i] fileName:fileName mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        DLog(@"上传进度--->%f",uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:nil];
        DLog(@"responseObject: %@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                [WHView showAlertwithTitle:@"入库成功" message:NSStringFormat(@"取件码%@", retDict[@"takeCode"])];
                self.deliverModel.balance = retDict[@"balance"];
                self.deliverModel.residue = retDict[@"residue"];
                [self configInfoView];
                
                if ([kUserDefaults boolForKey:OutVoice]) {
                    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ExpressInto.wav" withExtension:nil];
                    SystemSoundID soundID = 8789;
                    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
                    AudioServicesPlayAlertSound(soundID);
                }
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHView showMessage:@"上传失败" inView:self.view];
        [MBProgressHUD hideHUDForView:nil];
    }];
    
    
//    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_expressInto);
//
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                          @(userManager.detailUserInfo.userId), @"userId",
//                          self.deliverModel.expressUserId, @"expressUserId",
//                          self.barCodeStr, @"waybillNum",
//                          self.phoneNumberStr, @"mobile",
//                          self.expressName, @"expressCompany",
//                          nil];
//
//    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
//        DLog(@"%@", responseObject);
//        if (ValidDict(responseObject)) {
//            NSNumber *code = responseObject[@"errcode"];
//            NSString *errorMsg = responseObject[@"errmsg"];
//            if (code.intValue == 0) {
//                NSDictionary *retDict = responseObject[@"retobj"];
//                [WHView showAlertwithTitle:@"入库成功" message:NSStringFormat(@"取件码%@", retDict[@"takeCode"])];
//                self.deliverModel.balance = retDict[@"balance"];
//                self.deliverModel.residue = retDict[@"residue"];
//                [self configInfoView];
//
//                if ([kUserDefaults boolForKey:OutVoice]) {
//                    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ExpressInto.wav" withExtension:nil];
//                    SystemSoundID soundID = 8789;
//                    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
//                    AudioServicesPlayAlertSound(soundID);
//                }
//            } else {
//                [WHView showHudMsg:errorMsg];
//            }
//        }
//    } failure:^(NSError *error) {
//
//    }];
}

@end
